// ProcessList.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"

#include <iostream>
#include <stdio.h>
#include <string>
#include "windows.h"
#include "tlhelp32.h"
#include "Psapi.h"
#pragma comment(lib,"psapi.lib")

void describeMemoryForProcess(HANDLE process)
{
	PROCESS_MEMORY_COUNTERS memCounter;
	GetProcessMemoryInfo(process, &memCounter, sizeof(memCounter));
	_tprintf(TEXT("----Memory info (byte)-----\n"));
	_tprintf(TEXT("Peak working size %d\n"), memCounter.PeakWorkingSetSize);
	_tprintf(TEXT("Current working size %d\n"), memCounter.WorkingSetSize);
	_tprintf(TEXT("Peak page file usage %d\n"), memCounter.PeakPagefileUsage);
	_tprintf(TEXT("Current page file usage %d\n"), memCounter.PagefileUsage);
}

void listModulesForProcess(DWORD pid)
{
	HANDLE moduleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);
	MODULEENTRY32 moduleEntry;
	moduleEntry.dwSize = sizeof(MODULEENTRY32);
	if (!Module32First(moduleSnap, &moduleEntry))
	{
		_tprintf(TEXT("error in modules of process %d", pid));
		CloseHandle(moduleSnap);
		return;
	}
	
	_tprintf(TEXT("----DLL info-----\n"));
	do
	{
		_tprintf(TEXT("DLL name = %s\n"), moduleEntry.szModule);
	} while (Module32Next(moduleSnap, &moduleEntry));
}

int _tmain(int argc, _TCHAR* argv[])
{
	PROCESSENTRY32 entry;
	entry.dwSize = sizeof(PROCESSENTRY32);
	HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (!Process32First(snapshot, &entry))
	{
		_tprintf(TEXT("error in processes"));
		CloseHandle(snapshot);
		return 1;
	}
	if (snapshot != NULL)
	{
		do
		{
			wchar_t filepath[2000];
			HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, 0, entry.th32ProcessID);

			if (process)
			{
				GetProcessImageFileName(process, filepath, 2000);
				_tprintf(TEXT("\n\nProcess id = %d"), entry.th32ProcessID);
				_tprintf(TEXT("\tFull path = %s\n"), filepath);
				describeMemoryForProcess(process);
				CloseHandle(process);
			}
			listModulesForProcess(entry.th32ProcessID);
		} while (Process32Next(snapshot, &entry));
	}
	CloseHandle(snapshot);
	return 0;
}